package com.caigou.modules.query.ui.lingma

import android.os.Bundle
import android.text.TextUtils
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.screenCapture
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.utils.MediaUtils
import com.caigou.modules.query.databinding.ActivityLingMaBinding
import com.caigou.modules.query.viewmodel.LingMaViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2022/01/03
 */
@Route(path = RouterPath.Query.PAGE_LING_MA)
@AndroidEntryPoint
class LingMaActivity : BaseActivity() {
    private lateinit var binding: ActivityLingMaBinding

    private val lingMaViewModel: LingMaViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLingMaBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.lingMaFlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)

        binding.lingMaTvBack.setOnClickListener {
            finish()
        }

        binding.longMaIvShare.setOnClickListener {
            val bitmap = binding.lingMaFlContainer.screenCapture()
            MediaUtils.saveBitmap(this, bitmap)
            showToast("截图已保存到系统相册")
        }

        lingMaViewModel.getLingMaImg()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(lingMaViewModel.lingMaImgLiveData, ::handleGetLingMaImg)
    }

    private fun handleGetLingMaImg(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取生肖灵码异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                result.data?.apply {
                    ImageLoader.load(this@LingMaActivity, this, binding.lingMaIvCover)
                }
            }
        }
    }
}